package com.lhy.admin.service;

import com.github.pagehelper.PageHelper;
import com.lhy.admin.common.secure.authorization.Permissions;
import com.lhy.admin.mapper.DictMapper;
import com.lhy.admin.model.Dict;
import com.lhy.admin.model.extend.DictAttribute;
import com.lhy.commonweb.model.Page;
import com.lhy.commonweb.service.AbstractService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class DictService extends AbstractService<Dict, Integer> {

    public DictService(@Qualifier("dictMapper") Mapper<Dict> mapper) {
        super(mapper);
    }

    @Override
    public Page<Dict> query(Integer pageNumber, Integer pageSize, String sortColumns, Dict bean) {
        com.github.pagehelper.Page<Object> startPage = PageHelper.startPage(pageNumber, pageSize, sortColumns);
        List<Dict> select = DictMapper.class.cast(mapper).list(bean);
        return new Page<>(pageNumber, pageSize, (new BigDecimal(startPage.getTotal())).intValue(), select);
    }

    public List<Dict> listByCode(String code) {
        Example example = new Example(Dict.class);
        example.and().andEqualTo(Dict.FieldEnum.CODE.javaFieldName(), code);
        example.orderBy(Dict.FieldEnum.PRIORITY.javaFieldName()).asc();
        return this.query(example);
    }

    public void updateDict(DictAttribute bean) {
        //删除全部
        if (bean.getId() != null) {
            this.deleteCond(new Dict().setCode(bean.getCode()));
        }
        //再新增
        List<Dict> attributes = bean.getAttributes();
        if (!CollectionUtils.isEmpty(attributes)) {
            attributes.stream()
                    .map(dictAttributes -> dictAttributes.setCode(bean.getCode()).setDescription(bean.getDescription()).setStatus(1).setUpdated(new Date()))
                    .forEach(this::add);
        }
    }

}
